import React, { cloneElement, PropsWithChildren, ReactElement, useState } from 'react';
import { Badge, Button, Card, Descriptions, Divider, Drawer, message, Modal, Popconfirm, Spin, Table, Tag } from 'antd';
import { useRequest } from 'ahooks';
import { completeImgUrl } from "common/utils/utils";
import { evaluationCategory, EvaluationCategory, EvaluationStatus } from "common/utils/data";

import { evaluationV1AdminControllerShowEvaluation, evaluationV1AdminControllerUpdateEvaluationArticle } from "@/services/auto/evaluationAdmin";
import styles from './index.less';
import { VerticalAlignTopOutlined } from "@ant-design/icons";
import { blue } from "@ant-design/colors";
import DataViewer from "common/component/DataViewer";
import { useModel } from "@umijs/max";

interface Props {
  data: API.EvaluationAdminIndexResult;
  reload?: () => void;
}

export default function Detail(props: PropsWithChildren<Props>){
  const {data: globalConfigData} = useModel('global-config');

  const { data, reload, children } = props;

  const [visible,setVisible] = useState<boolean>(false);

  const {
    data: detail,
    run,
    loading,
  } = useRequest(()=>evaluationV1AdminControllerShowEvaluation({uuid: data.uuid}, {timeout: 300000}), {
    manual: true,
  });

  const {runAsync: patchRun} = useRequest(evaluationV1AdminControllerUpdateEvaluationArticle,{
    manual: true,
    onSuccess: (res, [_, req])=>{
      reload?.();
      if(req.isStick === undefined){
        setVisible(false);
      }else{
        run();
      }
      message.success('操作成功');
    }
  })

  return (<>
      {cloneElement(children as ReactElement, {
        onClick: ()=>{
          setVisible(true);
          run();
        }
      })}
    <Modal
      title="详情"
      onCancel={() => setVisible(false)}
      open={visible}
      width={1000}
      footer={
        <>
          {detail && (
            <div style={{ textAlign: 'right' }}>
              {detail.status === EvaluationStatus.UNPUBLISH && (
                <Popconfirm
                  title="确认发布吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun({uuid: detail.uuid}, {status: EvaluationStatus.PUBLISH});
                  }}
                >
                  <Button type="primary">发布</Button>
                </Popconfirm>
              )}
              {detail.status === EvaluationStatus.PUBLISH && (
                <Popconfirm
                  title="确认下架吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun({uuid: detail.uuid}, {status: EvaluationStatus.UNPUBLISH});
                  }}
                >
                  <Button danger type="primary">下架</Button>
                </Popconfirm>
              )}
            </div>
          )}
        </>
      }
    >
      <Spin spinning={loading}>
        {(!detail || !globalConfigData) && <div style={{ minHeight: '400px' }} />}
      </Spin>
      {detail && globalConfigData && (
        <Descriptions bordered size="small" className={styles.descLabelWidth}>
          <Descriptions.Item label="标题" span={3}>
            <Badge
              count={
                <Popconfirm
                  title={detail.article.isStick ? '取消当前置顶吗？' : '确认当前置顶吗？'}
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun(
                      {uuid: detail.uuid},
                      { isStick: detail.article.isStick === 1 ? 0 : 1 },
                    );
                  }}
                >
                  <VerticalAlignTopOutlined
                    style={{
                      color: detail.article.isStick ? blue.primary : 'initial',
                      fontSize: '18px',
                      cursor: 'pointer',
                    }}
                    title={detail.article.isStick ? '置顶中' : '未置顶'}
                  />
                </Popconfirm>
              }
            >
              {detail.title}
            </Badge>
          </Descriptions.Item>
          <Descriptions.Item label="分类" span={2}>
            {evaluationCategory[detail.category as EvaluationCategory]}
          </Descriptions.Item>
          <Descriptions.Item label="关键词" span={1}>
            {detail.article.keywords.map((item, index) => <Tag key={index}>{item}</Tag>)}
          </Descriptions.Item>
          <Descriptions.Item label="品牌" span={3}>
            {detail.brand.title}
          </Descriptions.Item>
          <Descriptions.Item label="缩略图" span={3}>
            {detail.article.thumbnails?.length ? <a
              href={completeImgUrl(detail.article.thumbnails[0])}
              target="_blank"
              className="flex justify-center"
            >
              <img src={completeImgUrl(detail.article.thumbnails[0])} alt="图片" className="h-40"/>
            </a> : '--'}
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={3}>
            {detail.article.desc}
          </Descriptions.Item>
          <Descriptions.Item label="正文内容" span={3}>
            {detail.showDatas.map((item, index) => {
              return (
                <DataViewer
                  key={item.uuid}
                  datas={item.children}
                  project={item.project}
                  targets={globalConfigData.targets}
                />
                /*<Card
                  style={{ width: '100%', margin: '15px 0' }}
                  key={item.uuid}
                >
                  <Card.Meta
                    title={item.project.name}
                    description={item.project.desc}
                  />
                  <Divider />
                  {(()=>{
                    if(item.project.type === EvaluationProjectType.DIGITAL){
                      return <DataViewer
                        datas={item.children}
                        project={item.project}
                      />
                    }
                    if(item.project.type === EvaluationProjectType.IMG){
                      return <>
                        {
                          item.children.map(childItem=>{
                            return <img src={completeImgUrl(childItem.img)} key={childItem.img} style={{marginBottom: 4}} />;
                          })
                        }
                      </>
                    }
                    if(item.project.type === EvaluationProjectType.TABLE){
                      return <>
                        {
                          item.children.map(childItem=>{
                            return <Table
                              title={childItem.name ? ()=>{
                                return childItem.name;
                              } : undefined}
                              columns={item.project.rule.columns.map(item=>{
                                return {
                                  ...item,
                                  dataIndex: item.key,
                                }
                              })}
                              dataSource={childItem.json as any[]}
                              pagination={false}
                              style={{marginBottom: 4}}
                              rowKey="id"
                            />;
                          })
                        }
                      </>
                    }
                    return <></>
                  })()}
                  <Card.Meta
                    style={{ marginTop: '10px' }}
                    title={item.children[0]?.desc}
                  />
                </Card>*/
              );
            })}
          </Descriptions.Item>
        </Descriptions>
      )}
    </Modal>
    </>
  );
};
